package com.glela.order.service.impl;

import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.glela.cache.redis.RedisKeys;
import com.glela.cache.redis.RedisUtil;
import com.glela.order.dao.PayTypeConfigDao;
import com.glela.order.model.PayTypeConfig;
import com.glela.order.service.PayTypeConfigService;

@Service
public class PayTypeConfigServiceImpl implements PayTypeConfigService {
	@Autowired
	private RedisUtil			redisUtil;
	@Autowired
	private PayTypeConfigDao	payTypeConfigDao;

	@Override
	public void cachePayType() {
		redisUtil.del(RedisKeys.ORDER_CFG_PAY_TYPE);
		List<PayTypeConfig> selectByStatus = payTypeConfigDao.selectByStatus(1);
		for (PayTypeConfig payTypeConfig : selectByStatus) {
			redisUtil.zadd(RedisKeys.ORDER_CFG_PAY_TYPE, payTypeConfig.getOrderNo(), JSON.toJSONString(payTypeConfig));
		}
	}

	@Override
	public Map<String, PayTypeConfig> getPayTypeConfig() {
		Set<String> zrange = _getCachePayTypes();
		Map<String, PayTypeConfig> rsltMap = new LinkedHashMap<>();
		for (String payTypeConfig : zrange) {
			PayTypeConfig parseObject = JSON.parseObject(payTypeConfig, PayTypeConfig.class);
			if (parseObject != null) {
				rsltMap.put(parseObject.getPayType().toString(), parseObject);
			}
		}
		return rsltMap;
	}

	@Override
	public List<PayTypeConfig> getPayTypeConfigs() {
		Set<String> zrange = _getCachePayTypes();

		LinkedList<PayTypeConfig> linkedList = new LinkedList<>();
		if (CollectionUtils.isNotEmpty(zrange)) {
			for (String payTypeConfig : zrange) {
				linkedList.add(JSON.parseObject(payTypeConfig, PayTypeConfig.class));
			}
		}
		return linkedList;
	}

	private Set<String> _getCachePayTypes() {
		Set<String> zrange = redisUtil.zrange(RedisKeys.ORDER_CFG_PAY_TYPE, 0, -1);
		if (CollectionUtils.isEmpty(zrange)) {
			cachePayType();
			zrange = redisUtil.zrange(RedisKeys.ORDER_CFG_PAY_TYPE, 0, -1);
		}
		return zrange;
	}

}
